//
//  MTPartyDetailHeaderCell.swift
//  MT
//
//  Created by ooops on 2020/5/26.
//  Copyright © 2020 张强. All rights reserved.
//

import UIKit
import Foundation
import Eureka
import MTCategory

protocol MTPartyDetailRemarkCellDelegate: NSObjectProtocol {
    /// 查看聚会任务申请信息
    func checkInviteInfo(canComm: Bool)
    /// 点击了用户头像
    func didSelectUserAvatar(user: JMSGUser)
}

public final class MTPartyRemarkRow: MTPartyRemarkCellRow, RowType {
    required public init(tag: String?) {
        super.init(tag: tag)
    }
}

open class MTPartyRemarkCellRow: MTPartyDetailRemarkCellRow {
    required public init(tag: String?) {
        super.init(tag: tag)
    }
}

extension MTPartyDetailRemarkCell: UICollectionViewDelegate, UICollectionViewDataSource {
    
    public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return users.count
    }
    
    public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell: MTPartyDetailAvatorCell = collectionView.dequeueReusableCell(withReuseIdentifier: MTPartyDetailAvatorCell.reuseIdentity(), for: indexPath) as! MTPartyDetailAvatorCell
        if let user = self.users[indexPath.item] {
            cell.bindAvator(user: user)
        }
        
        return cell
    }
    
    //MARK: UICollectionViewDelegate
    
    public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        if let user = self.users[indexPath.item] {
            self.delegate?.didSelectUserAvatar(user: user)
        }
    }
    
    public func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
        
    }
    
}

open class MTPartyDetailRemarkCell: Cell<String>, CellType {
    
    weak var delegate: MTPartyDetailRemarkCellDelegate?
    private var users: [JMSGUser?] = []
    /// 是否跳转沟通任务群
    private var canComm: Bool = false
    
    var model: MTPartyListModel? {
        didSet {
            if let remark = model?.detailResult?.remark {
                partyAddressLabel.text = remark
            }
            /// 申请人已经通过审核, 查看申请应当变更为, 去任务群沟通
            if model?.detailResult?.userName != JMSGUser.myInfo().username {
                inviteButton.isHidden = true
            } else if model?.detailResult?.userType == 2, model?.detailResult?.status == .accept {
                inviteButton.setTitle("沟通群", for: .normal)
                self.canComm = true
            }
            ///
            if let pushId = model?.detailResult?.pushId, let invite = model?.detailResult?.inviteNum {
                JMSGGroup.groupInfo(withGroupId: "\(pushId)") { [weak self] (result, error) in
                    guard let weakSelf = self else { return }
                    if let g: JMSGGroup = result as? JMSGGroup, error == nil {
                        g.memberInfoList({ (result, error) in
                            if error == nil {
                                if let userInfos: [JMSGGroupMemberInfo] = result as? [JMSGGroupMemberInfo] {
                                    weakSelf.users = userInfos.map { (info) -> JMSGUser? in
                                        return info.user
                                    }
                                    DispatchQueue.main.async {
                                        if weakSelf.users.count > 0 {
                                            weakSelf.collectionView.reloadData()
                                        }
                                        weakSelf.partyInfoLabel.text = "报名\(weakSelf.model?.detailResult?.signUserCount ?? 0)人 | 已通过\(userInfos.count)人 还差\(invite - userInfos.count)人"
                                        weakSelf.collectionView.snp.updateConstraints { (make) in
                                            make.height.equalTo(44)
                                        }
                                    }
                                }
                            }
                        })
                    }
                }
            } else {
                partyInfoLabel.text = "暂无人报名"
                collectionView.snp.updateConstraints { (make) in
                    make.height.equalTo(0)
                }
            }
            
            /*
             if let pushId = model?.detailResult?.pushId {
                 if let invite = model?.detailResult?.inviteNum {
                     JMSGGroup.groupInfo(withGroupId: "\(pushId)") { [weak self] (result, error) in
                         guard let weakSelf = self else { return }
                         if let g: JMSGGroup = result as? JMSGGroup, error == nil {
                             g.memberInfoList({ (result, error) in
                                 if error == nil {
                                     if let userInfos: [JMSGGroupMemberInfo] = result as? [JMSGGroupMemberInfo] {
                                         weakSelf.users = userInfos.map { (info) -> JMSGUser? in
                                             return info.user
                                         }
                                         DispatchQueue.main.async {
                                             if weakSelf.users.count > 0 {
                                                 weakSelf.collectionView.reloadData()
                                             }
                                             weakSelf.partyInfoLabel.text = "报名\(weakSelf.model?.detailResult?.signUserCount ?? 0)人 | 已通过\(userInfos.count)人 还差\(invite - userInfos.count)人"
                                             weakSelf.collectionView.snp.updateConstraints { (make) in
                                                 make.height.equalTo(44)
                                             }
                                         }
                                     }
                                 } else {
                                     weakSelf.partyInfoLabel.text = "报名\(weakSelf.model?.detailResult?.signUserCount ?? 0)人 | 已通过\(0)人 还差\(invite)人"
                                 }
                             })
                         }
                     }
                 } else {
                     partyInfoLabel.text = "暂无人报名"
                     collectionView.snp.updateConstraints { (make) in
                         make.height.equalTo(0)
                     }
                 }
             } else {
                 if let invite = model?.detailResult?.inviteNum {
                     self.partyInfoLabel.text = "报名\(self.model?.detailResult?.signUserCount ?? 0)人 | 已通过\(0)人 还差\(invite)人"
                 }
             }
             */
            
        }
    }

    public required init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
    }

    required public init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    
    /// 显示模式
    lazy var partyTimeLabel: UILabel = {
        let l = UILabel()
        l.font = PingFangSCSemiboldFont(14)
        l.textColor = UIColor.text.x1d1a1a
        l.text = "详细说明"
        l.setContentHuggingPriority(.defaultHigh, for: .horizontal)
        return l
    }()
    
    lazy var partyAddressLabel: UILabel = {
        let l = UILabel()
        l.font = PingFangSCMediumFont(12)
        l.textColor = UIColor.text.x9b9b9b
        l.numberOfLines = 0
        return l
    }()
    
    lazy var lineView: UIView = {
        let v = UIView()
        v.backgroundColor = UIColor.seprateLine.x707070
        return v
    }()
    
    lazy var partyInfoLabel: UILabel = {
        let l = UILabel()
        l.font = PingFangSCMediumFont(12)
        l.textColor = UIColor.text.x9b9b9b
        //l.text = "报名89人 | 已通过6人 还差1人"
        l.numberOfLines = 0
        return l
    }()
    
    lazy var inviteButton: UIButton = {
        let btn = UIButton(type: .custom)
        btn.setTitle("查看申请", for: .normal)
        btn.addTarget(self, action: #selector(MTPartyDetailRemarkCell.inviteInfo), for: .touchUpInside)
        btn.setTitleColor(UIColor(hex: 0x426bf2), for: .normal)
        btn.titleLabel?.font = PingFangSCMediumFont(12)
        return btn
    }()
    
    lazy var collectionView: UICollectionView = {
        /// 设置大小
//        let inset: CGFloat = 10.0
        let flowLayout = UICollectionViewFlowLayout()
        flowLayout.itemSize = CGSize(width: 44, height: 44)
//        flowLayout.minimumLineSpacing = 15
        flowLayout.minimumInteritemSpacing = 10.0
        flowLayout.scrollDirection = .horizontal
        let cv = UICollectionView(frame: CGRect(x: 0, y: 0, width: ScreenWidth, height: MiTuGiftView.collectionViewHeight), collectionViewLayout: flowLayout)
        cv.backgroundColor = UIColor.white
        cv.contentInset = UIEdgeInsets(top: 0, left: 18, bottom: 0, right: 18)
        cv.showsVerticalScrollIndicator = false
        cv.delegate = self
        cv.dataSource = self
        //        cv.isPagingEnabled = true
        cv.showsHorizontalScrollIndicator = false
        /// 注册 Cell
        cv.register(MTPartyDetailAvatorCell.self, forCellWithReuseIdentifier: MTPartyDetailAvatorCell.reuseIdentity())
        return cv
    }()
    
    
    @objc private func inviteInfo() {
        delegate?.checkInviteInfo(canComm: self.canComm)
    }
    
    open override func setup() {
        super.setup()
        backgroundColor = UIColor.theme.background
        selectionStyle = .none
        textLabel?.isHidden = true
        detailTextLabel?.isHidden = true
        editingAccessoryType =  .none
        row.disabled = Condition(booleanLiteral: true)
        self.height = { UITableView.automaticDimension }
        
        contentView.addSubview(partyTimeLabel)
        contentView.addSubview(partyAddressLabel)
        contentView.addSubview(lineView)
        
        contentView.addSubview(partyInfoLabel)
        contentView.addSubview(inviteButton)
        contentView.addSubview(collectionView)
        
        makeConstraint()
    }
    
    
    
    private func makeConstraint() {
        
        lineView.snp.makeConstraints { (make) in
            make.top.equalTo(partyAddressLabel.snp.bottom).offset(10)
            make.left.equalToSuperview().offset(18)
            make.right.equalToSuperview().offset(-18)
            make.height.equalTo(0.5)
        }
        
        partyTimeLabel.snp.makeConstraints { (make) in
            make.top.equalToSuperview().offset(12)
            make.left.equalToSuperview().offset(18)
            make.right.equalToSuperview().offset(-18)
            //make.width.greaterThanOrEqualTo(30)
        }
        
        partyAddressLabel.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(18)
            make.top.equalTo(partyTimeLabel.snp.bottom).offset(2)
            make.right.equalToSuperview().offset(-18)
            
        }
        
        partyInfoLabel.snp.makeConstraints { (make) in
            make.top.equalTo(lineView.snp.bottom).offset(10)
            make.left.equalTo(partyAddressLabel)
            make.right.equalTo(inviteButton.snp.left).offset(-18)
            make.height.equalTo(20)
        }
        
        inviteButton.snp.makeConstraints { (make) in
            make.centerY.equalTo(partyInfoLabel)
            make.right.equalToSuperview().offset(-18)
            //make.width.equalTo(0)
        }
        
        collectionView.snp.makeConstraints { (make) in
            make.top.equalTo(partyInfoLabel.snp.bottom).offset(15)
            make.right.left.equalToSuperview()
            make.height.equalTo(44)
            make.bottom.equalToSuperview().offset(-12)
        }
    }

    deinit {
//        datePicker.removeTarget(self, action: nil, for: .allEvents)
    }

    open override func update() {
        super.update()
//        if row.value != nil {
//            contentLabel.text = row.displayValueFor?(row.value)
//            contentLabel.font = PingFangSCSemiboldFont(14)
//            contentLabel.textColor = UIColor.text.x9b9b9b
//        }
    }

    open override func didSelect() {
        super.didSelect()
        row.deselect()
    }

    override open var inputView: UIView? {
        return nil
    }
}

open class MTPartyDetailRemarkCellRow: Row<MTPartyDetailRemarkCell>, NoValueDisplayTextConformance {

    open var noValueDisplayText: String? = nil

    required public init(tag: String?) {
        super.init(tag: tag)
        displayValueFor = { [unowned self] value in
            guard let val = value else { return nil }
            return val
        }
    }
}



